package org.kjtc;

import me.chanjar.weixin.common.WxType;
import me.chanjar.weixin.common.bean.WxAccessToken;
import me.chanjar.weixin.common.error.WxError;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.util.http.okhttp.OkHttpProxyInfo;
import org.junit.runner.RunWith;
import org.kjtc.redis.RedisUtil;
import org.kjtc.service.WebApplicationInitializerImpl;
import org.kjtc.wxapi.WxMpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import okhttp3.*;

import java.io.IOException;


/**
 * Created by Administrator on 2019/3/7 0007.
 * 获取access_token 放入到redis
 */
@RunWith(SpringRunner.class)
@SpringBootTest
public class GetAccessToken {
    @Autowired
    private RedisUtil redisUtil;

    private OkHttpProxyInfo httpProxy;
    @org.junit.Test
    public void getAccessToken(){
        //this.log.debug("WxMpServiceOkHttpImpl is running");
        //Lock lock = this.getWxMpConfigStorage().getAccessTokenLock();
        try {
            String appId = "wx0e82324b8c475e52";
            String Secret = "88b28b0d9bb46f5476f35d597c50e939";
           // lock.lock();
                String url = String.format(WxMpService.GET_ACCESS_TOKEN_URL,appId,Secret);

                Request request = new Request.Builder().url(url).get().build();
                OkHttpClient httpClient = new OkHttpClient();
                Response response = httpClient.newCall(request).execute();
                String resultContent = response.body().string();
                WxError error = WxError.fromJson(resultContent, WxType.MP);
                if (error.getErrorCode() != 0) {
                    try {
                        throw new WxErrorException(error);
                    } catch (WxErrorException e) {
                        e.printStackTrace();
                    }
                }
            WxAccessToken accessToken = WxAccessToken.fromJson(resultContent);
         String  token  =  accessToken.getAccessToken().replaceAll("\"","");
               //写入redis
            redisUtil.set("accessToken:temporaryKey",token);
        } catch (IOException e) {
            System.out.println("获取token失败");
        }
    }
}
